import {isNum} from '@/utils/utils'
import {isDate, isNull, isUndefined} from 'lodash'
import to from 'await-to-js'

const STORAGE_PREFIX = "KAOYAN_MP";
function initInsideData(data, opt = {}) {
  let insideData;
  const { expr, once } = opt;
  if (expr) {
    if (isNum(expr)) {
      if (expr > Date.now()) {
        insideData = { data, expr };
      }
    } else if (isDate(expr) && expr.getTime() > Date.now()) {
      insideData = { data, expr: expr.getTime };
    }
  } else if (once) {
    insideData = { data, once };
  } else {
    insideData = data;
  }
  return insideData;
}
function getInsideData(key, data) {
  if (isUndefined(data) || isNull(data)) return data;
  if (isNum(data.expr)) {
    if (data.expr >= Date.now()) return data.data;
    return null;
  } else if (data.once) {
    removeStorageSync(key);
    return data.data;
  }
  return data;
}
export const setStorageSync = (key, data, opt = {}) =>
  uni.setStorageSync(`${STORAGE_PREFIX}/${key}`, initInsideData(data, opt));
export const getStorageSync = (key) =>
  getInsideData(key, uni.getStorageSync(`${STORAGE_PREFIX}/${key}`));
export const removeStorageSync = (key) =>
  uni.removeStorageSync(`${STORAGE_PREFIX}/${key}`);
export const setStorage = (key, data, opt = {}) =>
  uni.setStorage({
    key: `${STORAGE_PREFIX}/${key}`,
    data: initInsideData(data, opt),
  });
export const getStorage = async (key, success, fail, complete) => {
  const [err, result] = await to(
    uni.getStorage({ key: `${STORAGE_PREFIX}/${key}` })
  );
  if (err) {
    fail && fail(err);
    complete && complete(err);
    return null;
  }
  success && success(getInsideData(key, result.data));
  complete && complete(result.data);
  return getInsideData(key, result.data);
};
export const removeStorage = async (key, success, fail, complete) => {
  const [err, result] = await to(
    uni.removeStorage({ key: `${STORAGE_PREFIX}/${key}` })
  );
  if (err) {
    fail && fail(err);
    complete && complete(err);
    return null;
  }
  success && success(result);
  complete && complete(result);
  return result;
};
